// 应用状态
class ChatApp {
  constructor() {
    this.socket = null;
    this.mqttClient = null;
    this.currentUser = null;
    this.currentRoom = null;
    this.isConnected = false;
    this.typingTimer = null;
    this.isTyping = false;

    this.init();
  }

  init() {
    this.bindEvents();
    this.checkConnection();
  }

  bindEvents() {
    // 登录表单
    const loginForm = document.getElementById("login-form");
    loginForm.addEventListener("submit", (e) => this.handleLogin(e));

    // 消息表单
    const messageForm = document.getElementById("message-form");
    messageForm.addEventListener("submit", (e) => this.handleSendMessage(e));

    // 消息输入框事件
    const messageInput = document.getElementById("message-input");
    messageInput.addEventListener("input", () => this.handleTyping());
    messageInput.addEventListener("keydown", (e) => {
      if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        this.handleSendMessage(e);
      }
    });

    // 界面按钮
    document
      .getElementById("leave-room")
      .addEventListener("click", () => this.leaveRoom());
    document
      .getElementById("toggle-users")
      .addEventListener("click", () => this.toggleUserSidebar());

    // 窗口关闭时断开连接
    window.addEventListener("beforeunload", () => {
      if (this.socket) {
        this.socket.disconnect();
      }
      if (this.mqttClient) {
        this.mqttClient.end();
      }
    });
  }

  async handleLogin(e) {
    e.preventDefault();

    const username = document.getElementById("username").value.trim();
    const room = document.getElementById("room").value;

    if (!username || !room) {
      this.showNotification("请填写完整信息", "warning");
      return;
    }

    this.currentUser = username;
    this.currentRoom = room;

    try {
      await this.connectToServer();
      this.switchToChat();
      this.updateRoomTitle();
    } catch (error) {
      console.error("连接失败:", error);
      this.showNotification("连接服务器失败，请检查网络", "error");
    }
  }

  async connectToServer() {
    // 连接Socket.IO
    this.socket = io({
      transports: ["websocket", "polling"],
      timeout: 20000,
      forceNew: true,
      reconnection: true,
      reconnectionDelay: 1000,
      reconnectionAttempts: 5,
      maxHttpBufferSize: 1e6,
    });

    return new Promise((resolve, reject) => {
      this.socket.on("connect", () => {
        console.log("Socket.IO连接成功");
        this.isConnected = true;
        this.updateConnectionStatus(true);

        // 加入聊天室
        this.socket.emit("join", {
          username: this.currentUser,
          room: this.currentRoom,
        });

        // 启用消息输入
        this.enableMessageInput();

        resolve();
      });

      this.socket.on("connect_error", (error) => {
        console.error("Socket.IO连接错误:", error);
        console.error("错误详情:", {
          message: error.message,
          description: error.description,
          context: error.context,
          type: error.type,
        });
        this.isConnected = false;
        this.updateConnectionStatus(false);
        this.showNotification(
          `连接失败: ${error.message || "网络错误"}`,
          "error"
        );
        reject(error);
      });

      // 添加更多错误监听
      this.socket.on("error", (error) => {
        console.error("Socket错误:", error);
        this.showNotification("连接出现错误，请刷新页面重试", "error");
      });

      this.socket.on("reconnect_error", (error) => {
        console.error("重连失败:", error);
        this.showNotification("重连失败，请检查网络", "error");
      });

      this.socket.on("disconnect", () => {
        console.log("Socket.IO连接断开");
        this.isConnected = false;
        this.updateConnectionStatus(false);
        this.disableMessageInput();
      });

      // 聊天消息
      this.socket.on("chat-message", (data) => {
        this.displayMessage(data);
      });

      // 用户加入
      this.socket.on("user-joined", (data) => {
        this.displaySystemMessage(data.message, data.timestamp);
        this.showNotification(`${data.username} 加入了聊天室`, "success");
      });

      // 用户离开
      this.socket.on("user-left", (data) => {
        this.displaySystemMessage(data.message, data.timestamp);
        this.showNotification(`${data.username} 离开了聊天室`, "warning");
      });

      // 在线用户列表
      this.socket.on("online-users", (users) => {
        this.updateUsersList(users);
      });

      // 用户正在输入
      this.socket.on("user-typing", (data) => {
        this.showTypingIndicator(data.username);
      });

      // 用户停止输入
      this.socket.on("user-stop-typing", (data) => {
        this.hideTypingIndicator(data.username);
      });

      // 连接超时
      setTimeout(() => {
        if (!this.isConnected) {
          reject(new Error("连接超时"));
        }
      }, 5000);
    });
  }

  handleSendMessage(e) {
    e.preventDefault();

    const messageInput = document.getElementById("message-input");
    const message = messageInput.value.trim();

    if (!message || !this.isConnected) {
      return;
    }

    // 发送消息
    this.socket.emit("chat-message", {
      message: message,
      room: this.currentRoom,
    });

    // 清空输入框
    messageInput.value = "";

    // 停止输入指示
    this.stopTyping();
  }

  handleTyping() {
    if (!this.isConnected) return;

    // 如果还没有开始输入，发送输入事件
    if (!this.isTyping) {
      this.isTyping = true;
      this.socket.emit("typing", { room: this.currentRoom });
    }

    // 重置计时器
    clearTimeout(this.typingTimer);
    this.typingTimer = setTimeout(() => {
      this.stopTyping();
    }, 1000);
  }

  stopTyping() {
    if (this.isTyping) {
      this.isTyping = false;
      this.socket.emit("stop-typing", { room: this.currentRoom });
    }
    clearTimeout(this.typingTimer);
  }

  displayMessage(data) {
    const messagesContainer = document.getElementById("messages");
    const messageElement = document.createElement("div");

    const isOwnMessage = data.username === this.currentUser;
    messageElement.className = `message ${isOwnMessage ? "own" : ""}`;

    const time = new Date(data.timestamp).toLocaleTimeString("zh-CN", {
      hour: "2-digit",
      minute: "2-digit",
    });

    messageElement.innerHTML = `
            <div class="message-content">
                ${
                  !isOwnMessage
                    ? `<div class="message-username">${data.username}</div>`
                    : ""
                }
                <div class="message-text">${this.escapeHtml(data.message)}</div>
                <div class="message-time">${time}</div>
            </div>
        `;

    messagesContainer.appendChild(messageElement);
    this.scrollToBottom();
  }

  displaySystemMessage(message, timestamp) {
    const messagesContainer = document.getElementById("messages");
    const messageElement = document.createElement("div");

    messageElement.className = "message system";

    const time = new Date(timestamp).toLocaleTimeString("zh-CN", {
      hour: "2-digit",
      minute: "2-digit",
    });

    messageElement.innerHTML = `
            <div class="message-content">
                <div class="message-text">${this.escapeHtml(message)}</div>
                <div class="message-time">${time}</div>
            </div>
        `;

    messagesContainer.appendChild(messageElement);
    this.scrollToBottom();
  }

  showTypingIndicator(username) {
    const indicator = document.getElementById("typing-indicator");
    const existingIndicator = indicator.querySelector(
      `[data-user="${username}"]`
    );

    if (!existingIndicator) {
      const span = document.createElement("span");
      span.setAttribute("data-user", username);
      span.textContent = `${username} 正在输入...`;
      indicator.appendChild(span);
    }
  }

  hideTypingIndicator(username) {
    const indicator = document.getElementById("typing-indicator");
    const userIndicator = indicator.querySelector(`[data-user="${username}"]`);

    if (userIndicator) {
      userIndicator.remove();
    }
  }

  updateUsersList(users) {
    const usersList = document.getElementById("users-list");
    const userCount = document.getElementById("user-count");

    usersList.innerHTML = "";
    userCount.textContent = users.length;

    users.forEach((username) => {
      const userElement = document.createElement("div");
      userElement.className = `user-item ${
        username === this.currentUser ? "current" : ""
      }`;
      userElement.innerHTML = `
                <i class="fas fa-circle"></i>
                <span>${this.escapeHtml(username)}</span>
            `;
      usersList.appendChild(userElement);
    });
  }

  switchToChat() {
    document.getElementById("login-screen").classList.remove("active");
    document.getElementById("chat-screen").classList.add("active");
  }

  updateRoomTitle() {
    const roomTitles = {
      general: "💬 综合讨论",
      tech: "💻 技术交流",
      random: "🎲 随机聊天",
      gaming: "🎮 游戏讨论",
    };

    const title = roomTitles[this.currentRoom] || this.currentRoom;
    document.getElementById("current-room").textContent = title;
  }

  updateConnectionStatus(connected) {
    const statusElement = document.getElementById("connection-status");

    if (connected) {
      statusElement.className = "status connected";
      statusElement.innerHTML = '<i class="fas fa-circle"></i> 已连接';
    } else {
      statusElement.className = "status disconnected";
      statusElement.innerHTML = '<i class="fas fa-circle"></i> 连接断开';
    }
  }

  enableMessageInput() {
    const messageInput = document.getElementById("message-input");
    const sendBtn = document.getElementById("send-btn");

    messageInput.disabled = false;
    sendBtn.disabled = false;
    messageInput.placeholder = "输入消息...";
  }

  disableMessageInput() {
    const messageInput = document.getElementById("message-input");
    const sendBtn = document.getElementById("send-btn");

    messageInput.disabled = true;
    sendBtn.disabled = true;
    messageInput.placeholder = "连接断开，无法发送消息";
  }

  leaveRoom() {
    if (this.socket) {
      this.socket.disconnect();
    }

    // 重置状态
    this.currentUser = null;
    this.currentRoom = null;
    this.isConnected = false;

    // 清空消息
    document.getElementById("messages").innerHTML = "";
    document.getElementById("users-list").innerHTML = "";
    document.getElementById("typing-indicator").innerHTML = "";

    // 重置表单
    document.getElementById("login-form").reset();

    // 切换到登录界面
    document.getElementById("chat-screen").classList.remove("active");
    document.getElementById("login-screen").classList.add("active");

    this.showNotification("已离开聊天室", "success");
  }

  toggleUserSidebar() {
    const sidebar = document.getElementById("users-sidebar");
    sidebar.classList.toggle("hidden");
  }

  scrollToBottom() {
    const messagesContainer = document.getElementById("messages");
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  }

  escapeHtml(text) {
    const div = document.createElement("div");
    div.textContent = text;
    return div.innerHTML;
  }

  showNotification(message, type = "info") {
    const container = document.getElementById("notifications");
    const notification = document.createElement("div");

    notification.className = `notification ${type}`;
    notification.textContent = message;

    container.appendChild(notification);

    // 自动移除通知
    setTimeout(() => {
      notification.style.animation = "notificationSlide 0.3s ease reverse";
      setTimeout(() => {
        if (notification.parentNode) {
          notification.parentNode.removeChild(notification);
        }
      }, 300);
    }, 3000);
  }

  checkConnection() {
    // 定期检查连接状态
    setInterval(() => {
      if (this.socket && !this.socket.connected && this.isConnected) {
        this.isConnected = false;
        this.updateConnectionStatus(false);
        this.disableMessageInput();
        this.showNotification("连接断开，正在尝试重连...", "warning");
      }
    }, 5000);
  }
}

// 应用启动
document.addEventListener("DOMContentLoaded", () => {
  window.chatApp = new ChatApp();

  // 开发模式下的调试信息
  if (window.location.hostname === "localhost") {
    console.log("MQTT聊天室已启动");
    console.log("连接地址:", window.location.origin);
  }
});
